$(function(){
	$(".mc").css("display","none");
	$('#categorys').hover(function(){
		$(this).children('.mc').toggle();
	});
	var $div_li = $("div.tab_title");
	$div_li.click(function() {
		$(this).toggleClass("selected");
		var index = $div_li.index(this);
		$("div.tab_box").eq(index).slideToggle("slow");
	}).hover(function() {
		$(this).addClass("hover");
	}, function() {
		$(this).removeClass("hover");
	});
	
	$('#login_btn').bind('click', subLoginFrm);
	$('#reg_btn').bind('click', subRegFrm);
	
	$("#pay").click(function(){
		$.ajax({
			type : 'POST',
			url : '/json?action=GET_MEMBER_SESSION_ACTION',
			cache : false,
			async : false,
			dataType : 'json',
			success : function(data){
				if(data.success){
					var obj  = data.root.MEMBER_SESSION;
					if(obj == undefined){
						drawWinValidateCode();
						$("#tclogincon").zxxbox({
							title : '登录/注册',
							show : winForm.clearTip()
						});
					} else {
						location.href = "step2.html";
					}
				}
			}
		});
	 });
	
	getCart();
	getFavList();
});

function addValue(id){
	var obj = $('#'+ id);
	var k = obj.val();
	obj.val(++k);
	updateCart();
}

function subtractValue(id){
	var obj = $('#'+ id);
	var k = obj.val();
	if (k > 0) {
		obj.val(--k);
	}
	updateCart(id);
}

function updateCart(id){
	var k = $("input[name='pid']");
	var v = $("input[name='AmountVlaue']");
	var elements = [];
	$.each(k, function(i, obj){
		var bo = {};
		bo.id = parseInt(obj.value);
		bo.qty = parseInt(v[i].value);
		elements.push(bo);
	});
	var url = '/json?action=UPDATE_PRODUCT_TO_CART_ACTION';
	$.post(url,{PRODUCT:JSON.stringify(elements)},function(data){
		if(data.success){
			getCart(id);
		}
	},'json');
}

function getCart(id){
	var url = '/json?action=QUERY_CART_BY_MEMBER_ACTION';
	$.post(url,{},function(data){
		if(data.success){
			var status = data.root.STATUS.rs[0];
			var cart = data.root.CART.rs[0].PRODUCT_LIST;
			var items = data.root.CART.rs[0].ITEMS;
			var amount = data.root.CART.rs[0].AMOUNT;
//			$('#cart_items').html(items);
			$('#amount').html('￥'+ amount);
			var listNode = $('#cart_list');
			listNode.html('');
			if(items == 0){
				$('.shopping_table').hide();
				$('.cart-empty').show();
				return;
			}
			$('.cart-empty').hide();
			$('.shopping_table').show();
			var productCount = 0;
			var balanceAmount = 0;
			$.each(cart,function(i, obj){
				var balance = 0.00;
				if(obj.MARKET_PRICE > obj.MEMBER_PRICE){
					balance = obj.MARKET_PRICE - obj.MEMBER_PRICE;
				}
				
				var divStr = [
					'<tr>',
					    '<td>'+ obj.PRODUCT_NO +'</td>',
					    '<td class="shopping_table_img"><i><a href="../product/file.html?id='+obj.PRODUCT_ID+'" target="blank"><img src="../upload/product/'+obj.PRODUCT_NO+'.jpg" /></a></i><p><a href="../product/file.html?id='+obj.PRODUCT_ID+'" target="blank">'+ obj.PRODUCT_NAME +'</a></p></td>',
					    '<td class="market_price">&nbsp;&nbsp;￥'+ (obj.MARKET_PRICE).toFixed(2) +'&nbsp;&nbsp;</td>',
					    '<td><span>￥'+ (obj.MEMBER_PRICE).toFixed(2) +'</span></td>',
					    '<td class="balance_bg"><div class="balance">￥'+ balance.toFixed(2) +'</div></td>',
					    '<td><div class="shop_sun"><a href="javascript:subtractValue(\'AmountVlaue'+i+'\');"><img src="../images/jianbtn.gif" /></a><input id="AmountVlaue'+i+'" name="AmountVlaue" type="text" value="'+obj.QTY+'" size="5" maxlength="5" onpaste="return false;" onkeypress="return listenerKeypress();" onkeyup="listenerKeyUp(\'AmountVlaue'+i+'\');"/><input type="hidden" name="pid" value="'+obj.PRODUCT_ID+'" /><a href="javascript:addValue(\'AmountVlaue'+i+'\');"><img src="../images/jiabtn.gif" /></a></div></td>',
					    '<td><span>￥'+ (obj.AMOUNT).toFixed(2) +'</span></td>',
					    '<td><a href="javascript:void(0)" onclick="favProduct('+obj.PRODUCT_ID+',this);">[加入收藏夹]</a> <a href="javascript:void(0)" onclick="deleteProduct(\'AmountVlaue'+i+'\')">[删除]</a></td>',
				  	'</tr>'
				].join('');
				listNode.append(divStr);
				productCount += obj.QTY;
				balanceAmount += balance*obj.QTY;
			});
			$('#product_count').html(productCount);
			$('#balanceAmount').html('￥'+ balanceAmount.toFixed(2));
			
			if(id){
				$('#'+id).focus();
			}
		}
	},'json');
}

function listenerKeypress(){
	var keyCode = event.keyCode;
	return ((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode == 46);
}

function listenerKeyUp(id){
	if(!listenerKeypress()){
		return;
	}
	
	var obj = $('#'+ id);
	var v = obj.val();
	if(v.length == 0){
		obj.val(1);
	}
	updateCart(id);
}

function favProduct(id,btn){
	$.ajax({
		type : 'POST',
		url : '/json?action=GET_MEMBER_SESSION_ACTION',
		cache : false,
		async : false,
		dataType : 'json',
		success : function(data){
			if(data.success){
				var obj  = data.root.MEMBER_SESSION;
				if(obj == undefined){
					$("#tclogincon").zxxbox({
						title : '登录/注册'
					});
					drawWinValidateCode();
				} else {
					var url = '/json?action=ADD_T_PRODUCT_FAVORITES_ACTION&PRODUCT_ID=' + id;
					$.post(url,{}, function(data){
						if(data.success){
							var tip = $('#success_tip');
							$('#info_tip').html('已加入收藏夹');
							showTip(tip,btn,25,5);
							getFavList();
						}
					},'json');
				}
			}
		}
	});
}

var timer;
function showTip(tip, btn, left, top){
	var offset = $(btn).offset();
	tip.css('left', offset.left - left);
	tip.css('top', offset.top - top);
	tip.show();
	
	if (timer) {
		clearTimeout(timer);
	}
	timer = setTimeout("closeTip()", 1000);
}

function closeTip() {
	$('#success_tip').fadeOut('slow');
	timer=null;
}

function deleteProduct(id){
	$('#'+ id).val(0);
	updateCart();
}

function getFavList() {
	var url = '/json?action=QUERY_T_PRODUCT_FAVORITES_LIST_ACTION';
	var pageSize = 5;
	var defaultHtml = '<div style="text-align:center; padding-top:50px;padding-bottom:50px;">您还没有收藏任何商品...</div>';
	var current = $Util.getQueryString(document.location.search,'current');
	$UI.changePage(url,pageSize,'T_PRODUCT_FAVORITES','#fav_list',printFav,'#pager',defaultHtml,current);
}

function printFav(obj,result,i,n,len,c,t) {
	var div = [
		'<li>',
			'<a href="../product/file.html?id='+obj.PRODUCT_ID+'" target="blank"><img src="../upload/product/'+obj.PRODUCT_NO+'.jpg"/></a>',
			'<div>',
				'<p><a href="../product/file.html?id='+obj.PRODUCT_ID+'"  target="blank">',obj.PRODUCT_NAME,'</a></p>',
				'<p>市场价：<del>￥',obj.MARKET_PRICE,'</del>&nbsp;&nbsp;金麟价：<span class="cRed">￥',obj.MEMBER_PRICE,'</span></p>',
				'<p align="center"><input type="button" onClick="addCart('+obj.PRODUCT_ID+')" class="btn_gwc" value="" /></p>',
			'</div>',
		'</li>'
	].join('');		
	$(result).append(div);
}

function addCart(id){
	var url = '/json?action=ADD_PRODUCT_TO_CART_ACTION';
	$.post(url,{
			PRODUCT_ID:id,
			QTY : 1
		},function(data){
		if (data.success) {
			getCart(id);
		} else {
			alert(data.errors.errmsg);
		}
	},'json');
}

function subLoginFrm(){
	if(!winForm.checkLoginForm()){
		return;
	}
	
	var options = {
	    dataType: 'json',
	    success: function(data) {
	    	if(data.success){
	    		location.href = "step2.html";
	      	} else {
	      		var o = $('#win_login_message');
	      		o.html(data.errors.errmsg);
	      		o.show();
	      	}
	   	}
	};
	$.ajaxSetup({contentType:'application/x-www-form-urlencoded;charset=utf-8'});
    $('#login_frm').ajaxSubmit(options);
}

function subRegFrm(){
	if(!winForm.checkRegForm()){
		return;
	}
	var options = {
	    dataType: 'json',
	    success: function(data) {
	    	if(data.success){
	      		location.href = "step2.html";
	      	} else {
	      		var o = $('#win_reg_message');
	      		o.html(data.errors.errmsg);
	      		o.show();
	      		drawWinValidateCode();
	      	}
	   	}
	};
	$.ajaxSetup({contentType:'application/x-www-form-urlencoded;charset=utf-8'});
    $('#reg_frm').ajaxSubmit(options);
}
